<template>
    <div class="customer_base_sop_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
        <ZwTable
            ref="sopTableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button @click="highSet">高级设置</el-button>
                <el-button type="primary" @click="creatSop">创建SOP</el-button>
            </template>
        </ZwTable>
    </div>
    <Dialog :app-dialog="appDialog">
        <div class="title">确定要删除该SOP规则吗?</div>
    </Dialog>
    <ZWadvancedSetup ref="advanced" :type="5"></ZWadvancedSetup>
    <Taskdetail ref="taskdetail" :type="2" :tooltip="tooltip"></Taskdetail>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CUSTOMER_BASE_SOP' });
</script>

<script lang="tsx" setup>
import Dialog from '@/components/Dialog.vue';
import { computed, reactive, ref, nextTick, onActivated } from 'vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWadvancedSetup from '@/components/ZWadvancedSetup.vue';
import Taskdetail from '../components/Taskdetail.vue';
import { ElButton, ElMessage, ElScrollbar, ElPopover } from 'element-plus';
import { deepCopy } from '@/utils/helper';
import { groupSopList, groupSopStatus, delGroupSop } from '@/api/smartMarketing/sop';
import { getCreateList } from '@/api/common';
import router from '@/router';
import { div } from '@/utils/math';

const sopTableRef = ref(null);
const advanced: any = ref(null);
const taskdetail: any = ref(null);
const sopRuleId = ref();
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const defaultParams = reactive({
    name: '',
    created_uids: [],
    groupchat_id: [],
    status: '',
    created_time: []
});
const sopBtnList = reactive([
    { id: 1, val: '开启', authCode: 'OPEN_BASE_SOP' },
    { id: 2, val: '关闭', authCode: 'CLOSE_BASE_SOP' },
    { id: 3, val: '查看', authCode: 'LOOK_BASE_SOP' },
    { id: 4, val: '编辑', authCode: 'EDIT_BASE_SOP' },
    { id: 5, val: '执行详情', authCode: 'FINISH_BASE_SOP' },
    { id: 6, val: '克隆规则', authCode: 'COPY_BASE_SOP' },
    { id: 7, val: '删除', authCode: 'DEL_BASE_SOP' }
]);
const tooltip = {
    mass_num: {
        title: '执行群发数',
        text: '触达方式为：群主消息群发时，当群主在收到群发助手的消息提醒时，点击“发送”的群发数。'
    },
    fail_num: {
        title: '执行失败数',
        text: '触达方式为：群主消息群发时，当群主点击“发送”后，发送结果中有客户群“接收次数已达上限”的群发数'
    },
    letter_num: { title: '群主发消息完成数', text: '执行群发失败后，群主手动发送群消息完成的任务数。' }
};
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '规则名称',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入规则名称'
        },
        {
            label: '创建人',
            name: 'created_uids',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },

        {
            label: '选择群主',
            name: 'groupchat_id',
            value: [],
            type: 'select',
            placeholder: '请选择群主',
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: 'SOP状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '请选择SOP状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            {
                                name: '全部',
                                id: 0
                            },
                            {
                                name: '已开启',
                                id: 1
                            },
                            {
                                name: '已关闭',
                                id: 2
                            }
                        ]);
                    }, 300);
                });
            },
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
            // 设置结束日期时间为 23:59:59，设完日期不能点击 elment-plus bug？
            // defaultTime: ['00:00:00', '23:59:59']
        }
    ];
});
const tableOption = [
    {
        prop: 'name',
        label: 'SOP规则名称',
        minWidth: 240
    },
    {
        prop: 'user_name',
        label: '创建人',
        width: 180,
        render({ row }: any) {
            return (
                <div>
                    <span>{row.user_name ? row.user_name : '--'}</span>
                </div>
            );
        }
    },
    {
        prop: 'trigger_range',
        label: '群主',
        minWidth: 300,
        showOverflowTooltip: true,
        render({ row }: any) {
            const slotReference = () => (
                <div>
                    {row.workuser.map((item: any, index: any) => {
                        if (index <= 1) {
                            return (
                                <div class="group">
                                    <img width="36" height="36" style="border-radius: 4px" src={item.avatar} alt="" />
                                    <div class="group_info">
                                        <p class="group_info_title">
                                            <span class="text">{item.name} </span>
                                        </p>
                                    </div>
                                </div>
                            );
                        }
                    })}
                </div>
            );
            const slotDefault = () => (
                <div>
                    <ElScrollbar maxHeight="260px">
                        {row.workuser.map((item: any) => {
                            return (
                                <div style={popStyle}>
                                    <img width="36" height="36" src={item.avatar} alt="" />
                                    <div style="margin-left: 10px">
                                        <p style="line-height: 18px, font-size: 14px,display: flex,align-items: center;">
                                            <span style="display: inline-block,max-width: 130px,white-space: nowrap, text-overflow: ellipsis, overflow: hidden ">
                                                {item.name}
                                            </span>
                                        </p>
                                    </div>
                                </div>
                            );
                        })}
                    </ElScrollbar>
                </div>
            );
            return (
                <div>
                    <div v-show={row.workuser.length <= 2}>
                        {row.workuser.map((item: any) => {
                            return (
                                <div class="group">
                                    <img width="36" height="36" style="border-radius: 4px" src={item.avatar} alt="" />
                                    <div class="group_info">
                                        <p class="group_info_title">
                                            <span class="text">{item.name} </span>
                                        </p>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                    <div v-show={row.workuser.length > 2}>
                        <ElPopover
                            placement="top-start"
                            popper-class="popGroup"
                            trigger="hover"
                            vSlots={{ reference: slotReference, default: slotDefault }}
                            width={300}
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'status',
        label: 'SOP状态',
        width: 180,
        render({ row }: any) {
            return (
                <div>
                    <p>{row.status == 1 ? <span style="color:#60B900">已开启</span> : '已关闭'}</p>
                </div>
            );
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 260
    },
    {
        prop: 'validity_type',
        label: '有效期',
        width: 330,
        render({ row }) {
            return (
                <>
                    {row.validity_type == 1 ? (
                        <span>永久</span>
                    ) : (
                        <span>
                            {row.start_time} ~ {row.end_time}
                        </span>
                    )}
                </>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 300,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }: any) {
            return sopBtnList.map((item: any, index: number) => {
                return (
                    <ElButton
                        size="small"
                        v-auth={item.authCode}
                        v-show={item.id != row.status}
                        disabled={row.status != 2 ? (item.id == 4 || item.id == 7 ? true : false) : false}
                        onClick={() => sopBtn(row, item.id)}>
                        {item.val}
                    </ElButton>
                );
            });
        }
    }
];
const creatSop = () => {
    router.push('/smartMarketing/marketAutomation/customerBaseSop/createBaseSop');
};
// 获取表格高度
const getTableH = () => {
    nextTick(() => {
        sopTableRef.value.getTableH();
    });
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return groupSopList;
};
const search = (data: any) => {
    currentParams.value = data;
    state.searchParams = deepCopy(data);
};
const reset = (v: any) => {
    state.searchParams = deepCopy(defaultParams);
    currentParams.value = null;
};
const sopBtn = (btn: any, num: number) => {
    const status = (val: number) => {
        const params = {
            market_sop_id: btn.id,
            status: val
        };
        groupSopStatus(params)
            .then((res: any) => {
                sopTableRef.value.reload();
                ElMessage.success('SOP状态修改成功');
            })
            .catch((e: any) => {
                ElMessage.error('SOP状态修改失败');
            });
    };
    let text = '';
    let name: string;
    let name2: number | string;
    let isCopy: number;
    let t: string;
    switch (num) {
        case 1:
            status(1);
            break;
        case 2:
            status(2);
            break;
        case 3:
            router.push('/smartMarketing/marketAutomation/customerBaseSop/createBaseSop?type=look&&id=' + btn.id);
            break;
        case 4:
            router.push('/smartMarketing/marketAutomation/customerBaseSop/createBaseSop?type=edit&&id=' + btn.id);
            break;
        case 5:
            taskdetail.value.drawer = true;
            taskdetail.value.drawerData = btn;
            taskdetail.value.defaultParams.sop_id = btn.id;
            break;
        case 6:
            name = btn.name.substring(btn.name.length - 3);
            isCopy = btn.name.search('-副本');
            if (isCopy != -1) {
                if (name.length <= 3) {
                    name2 = name.substring(name.length - 1);
                    if (name2 >= 1) {
                        t = btn.name.slice(0, btn.name.length - 4);
                        text = t + '-副本' + (+name2 + 1);
                    } else {
                        text = btn.name + 2;
                    }
                }
            } else {
                text = btn.name + '-副本';
            }
            router.push({
                path: '/smartMarketing/marketAutomation/customerBaseSop/createBaseSop',
                query: { id: +btn.id, type: 'copy', copy: text }
            });
            break;
        case 7:
            appDialog.visible = true;
            sopRuleId.value = btn.id;
            break;
    }
};
const cancelHandel = () => {
    appDialog.visible = false;
};
const submitHandel = () => {
    delGroupSop({ market_sop_id: sopRuleId.value }).then((res: any) => {
        ElMessage.success('删除成功');
        cancelHandel();
        sopTableRef.value.reload();
    });
};
// 高级设置
const highSet = () => {
    advanced.value.isShow = true;
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: '提示',
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
onActivated((val: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
const popStyle = {
    width: '227px',
    height: '48px',
    ['border-radius']: '2px',
    padding: '6px',
    border: '1px solid #eaeaea',
    display: 'flex',
    ['align-items']: 'center',
    margin: '5px 0'
};
const style = {
    ['font-size']: '12px',
    color: '#969696'
};
</script>
<style lang="scss" scoped>
.customer_base_sop_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

:deep(.sopBtn) {
    padding: 4px 16px 2px;
    margin: 3px;
    min-height: 0;
}

:deep .group {
    width: 227px;
    height: 48px;
    border-radius: 2px;
    padding: 6px;
    box-sizing: border-box;
    border: 1px solid #eaeaea;
    display: flex;
    align-items: center;
    margin: 5px 0;

    &_info {
        margin-left: 10px;

        &_title {
            line-height: 18px;
            font-size: 14px;
            display: flex;
            align-items: center;

            .text {
                display: inline-block;
                max-width: 130px;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }
        }

        &_user {
            color: #969696;
            font-size: 12px;
        }
    }
}

.title {
    text-align: center;
    padding: 50px 0;
}
</style>
